package com.bobi.tfca.ui.mainnavigation.home

import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.graphics.BitmapFactory
import android.media.RingtoneManager
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.lifecycle.ViewModel
import androidx.viewpager2.widget.ViewPager2
import com.bobi.doublewillow.utils.SPUtil
import com.bobi.tfca.R
import com.bobi.tfca.base.BaseFragment
import com.bobi.tfca.databinding.FragmentHomeBinding
import com.bobi.tfca.model.Callback
import com.bobi.tfca.model.LoginStatus
import com.bobi.tfca.network.ApiResponse
import com.bobi.tfca.network.api.MessageAPI
import com.bobi.tfca.network.client.AppCache
import com.bobi.tfca.network.response.MemberResponse
import com.bobi.tfca.network.response.MessageResponse
import com.bobi.tfca.ui.adapter.HomePagerAdapter
import com.bobi.tfca.ui.mainnavigation.home.activity.ActivityFragment
import com.bobi.tfca.ui.mainnavigation.home.culture.CultureFragment
import com.bobi.tfca.ui.mainnavigation.home.rights.MemberRightsFragment
import com.bobi.tfca.ui.mainnavigation.home.rules.AssRulesFragment
import com.bobi.tfca.ui.mainnavigation.home.structure.OrgStructureFragment
import com.bobi.tfca.util.LogUtil
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
import java.util.Timer
import java.util.TimerTask


class HomeFragment : BaseFragment<FragmentHomeBinding, ViewModel>(
    FragmentHomeBinding::inflate,
    null,
    true
) {
    private lateinit var viewPager: ViewPager2
    private lateinit var tabLayout: TabLayout
    private lateinit var pagerAdapter: HomePagerAdapter
    private var timer: Timer = Timer()
    private lateinit var notificationManager: NotificationManagerCompat

    private var task: TimerTask = object : TimerTask() {
        override fun run() {
            try {
                checkNewMessage()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    @SuppressLint("ResourceType", "UseRequireInsteadOfGet")
    override fun initFragment(
        binding: FragmentHomeBinding,
        viewModel: ViewModel?,
        savedInstanceState: Bundle?
    ) {
        // 设置topPanel
        setTopPanelStyle(binding)

        // 初始化ViewPager
        viewPager = binding.tablayoutViewpager
        pagerAdapter = HomePagerAdapter(this).apply {
            add { CultureFragment() }
            add { ActivityFragment() }
            add { OrgStructureFragment() }
            add { MemberRightsFragment() }
            add { AssRulesFragment() }
        }
        viewPager.adapter = pagerAdapter

        // 初始化tablelayout
        tabLayout = binding.tabLayout
        TabLayoutMediator(tabLayout, viewPager) { tab, position ->
            when (position) {
                0 -> tab.text = "文化展示"
                1 -> tab.text = "活动"
                2 -> tab.text = "组织架构"
                3 -> tab.text = "会员权益"
                4 -> tab.text = "协会章程"
            }
        }.attach()

        // 设置登录信息
        val myLoginInfo = AppCache.getMyInfo()
        if (myLoginInfo == null) {
            val loginInfoStr: String =
                publicViewModel!!.spUtil.getItem(SPUtil.MY_LOGIN_INFO, "") as String
            LogUtil.i("loginInfoStr:$loginInfoStr")
            if ("" != loginInfoStr) {
                val gson = Gson()
                val loginInfo: MemberResponse =
                    gson.fromJson(loginInfoStr, MemberResponse::class.java)
                // 设置AppCache
                AppCache.setMyInfo(loginInfo)
                // 设置登录状态
                val token = publicViewModel!!.spUtil.getItem(SPUtil.MY_TOKEN, "") as String
                LogUtil.i(loginInfo.toString() + "\n" + token)
                publicViewModel!!.requestBuilder.authorization(token)
                // 请求元素列表，以便设置可见性
                publicViewModel!!.getCurrentAllMenus()
                if (AppCache.checkSocketConnectStatus()) {
                    AppCache.updateStatus(LoginStatus.CONNECTED)
                } else {
                    AppCache.updateStatus(LoginStatus.UNCONNECTED)
                }
            } else {
                // 请求元素列表，以便设置可见性
                publicViewModel!!.getCurrentAllMenus()
            }
        }
    }

    private fun connectSocket() {
        // 连接socket
        // 设置状态为连接未建立
        if (!AppCache.checkSocketConnectStatus()) {
            if (AppCache.checkLoginStatus()) {
                if (AppCache.getService() != null) {
                    // 登录成功，建立socket
                    AppCache.getService()
                        .login() { code: Int, msg: String, aVoid: Void? ->
                            if (code == 200) {
                            } else {
                                Toast.makeText(
                                    requireContext(),
                                    "建立Socket失败 稍后重试",
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        }
                }
            }
        }
    }

    private fun registerForNotification() {
        notificationManager = NotificationManagerCompat.from(this.requireActivity())
        // 在MainActivity 或其他合适的地方创建通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = "new_message"  //通知渠道的标识符
            val channelName = "Message"    //通知渠道的位置
            val channelDescription = "来自协会的消息"    //通知渠道的描述

            // 设置通知渠道的级别
            val importance = NotificationManager.IMPORTANCE_HIGH

            // 创建通知渠道
            val notificationChannel = NotificationChannel(channelId, channelName, importance)
            notificationChannel.setDescription(channelDescription)

            // 在系统中注册消息
            notificationManager.createNotificationChannel(notificationChannel)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 注册通知管理
        registerForNotification()

        Thread {
            do {
                LogUtil.i("建立Socket连接，设置通知回调")
                Thread.sleep(4000);
                // 检查Socket连接
                val loginStatus = AppCache.checkLoginStatus()
                if (loginStatus) {
                    LogUtil.i("处于登录状态")
                    connectSocket() // 执行连接建立操作
                    setNotificationCallback()
                }
            } while (AppCache.getService() == null)
            LogUtil.i("连接线程结束")
        }.start()


        // 一分钟执行一次
        timer.schedule(task, 1000 * 60 * 1, 1000 * 60 * 1)
    }

    private fun setNotificationCallback() {
        if (AppCache.getService() != null) {
            // 收信息显示
            AppCache.getService().setNotificationCallback(notificationCallback)
            val connect = AppCache.checkSocketConnectStatus()
            if (!connect) {
                AppCache.getService()
                    .login() { code: Int, msg: String, aVoid: Void? ->
                    }
            }
        }
    }


    private fun checkNewMessage() {
        publicViewModel!!.apply {
            request(MessageAPI::class.java).checkNewMessage().getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                val res = it.data
                                if (res?.code == 200) {
                                    // 发通知
                                    // 如果在当前页面就不发通知，不在才发，后续可以优化为在应用内将底栏消息图标改为有消息样式，不在应用内才是发通知
                                    val fragmentManager = requireActivity().supportFragmentManager
                                    if (fragmentManager.findFragmentById(R.id.messageFragment) == null || !fragmentManager.findFragmentById(
                                            R.id.messageFragment
                                        )!!.isVisible
                                    ) {
                                        val title = "消息"
                                        val contentText = "你有新的消息"
                                        LogUtil.i("定时器发送通知" + it.data.msg)
                                        // 显示一个通知
                                        val notification = createNotification(title, contentText)
                                        notificationManager.notify(3, notification)
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 收信息显示
     */
    private val notificationCallback =
        Callback<MessageResponse> { code, msg, message ->
            // 发通知
            val fragmentManager = requireActivity().supportFragmentManager
            if (fragmentManager.findFragmentById(R.id.messageFragment) == null || !fragmentManager.findFragmentById(
                    R.id.messageFragment
                )!!.isVisible
            ) {
                LogUtil.i("消息界面不可见，发送通知------------")
                val title = "消息"
                val contentText = "你有新的群聊消息"
                //显示一个通知
                val notification = createNotification(title, contentText)
                notificationManager.notify(2, notification)
            }
            LogUtil.i("消息界面可见，不发送通知------------")
        }

    private fun createNotification(title: String, contentText: String): Notification {
        // 获取目标Fragment的PendingIntent
//        val intent = Intent(requireContext(), MainActivity::class.java)
        // 暂时不会如何返回之前应用的状态，直接重启的应用
        val intent =
            requireContext().packageManager.getLaunchIntentForPackage(requireContext().packageName)
        intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
        val pendingIntent = PendingIntent.getActivity(
            requireContext(), 0, intent,
            PendingIntent.FLAG_IMMUTABLE
        )
        // 创建通知
        val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
        val notification: Notification =
            NotificationCompat.Builder(this.requireActivity(), "new_message")
                .setAutoCancel(true)
                .setContentTitle(title) //消息的标题
                .setContentText(contentText) //消息的内容
                .setWhen(System.currentTimeMillis()) //指定通知被创建的时间
                .setSmallIcon(R.mipmap.ic_launcher) //通知的小图标
                .setLargeIcon(
                    BitmapFactory.decodeResource(
                        resources,
                        R.mipmap.ic_launcher
                    )
                ) //通知的大图标
                .setContentIntent(pendingIntent)
                .setSound(soundUri)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setOnlyAlertOnce(true)
                .build()
        return notification
    }

    /**
     * 设置顶部面板的样式
     */
    private fun setTopPanelStyle(binding: FragmentHomeBinding) {
        val topPanel = binding.topPanel
        val leftLayout = topPanel.leftLayout
        leftLayout.visibility = View.GONE
        val rightLayout = topPanel.rightLayout
        rightLayout.visibility = View.GONE
        topPanel.titleText.visibility = View.GONE
    }

    override fun onDestroyView() {
        super.onDestroyView()
        viewPager.adapter = null
    }

    override fun resumeFragment(viewModel: ViewModel?) {
        super.resumeFragment(viewModel)
        if (viewPager.adapter == null) {
            pagerAdapter = HomePagerAdapter(this).apply {
                add { CultureFragment() }
                add { ActivityFragment() }
                add { OrgStructureFragment() }
                add { MemberRightsFragment() }
                add { AssRulesFragment() }
            }
            viewPager.adapter = pagerAdapter
        }
        // 请求元素列表，以便设置可见性
        publicViewModel!!.getCurrentAllMenus()
    }


    override fun onDestroy() {
        super.onDestroy()
        LogUtil.i("首页被销毁了")
        timer.cancel()
        AppCache.getService().setNotificationCallback(null)
    }
}